package modelo;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class PedidoDAO implements Serializable {	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	Connection con;
	
	public PedidoDAO() {
		conecta("sun.jdbc.odbc.JdbcOdbcDriver","jdbc:odbc:database", "username", "password");
	}

	public PedidoDAO(char tipo){
		switch(tipo){
			// l = local
			case 'l' : conecta("sun.jdbc.odbc.JdbcOdbcDriver","jdbc:odbc:database", "username", "password"); break;
			// r = remota
			case 'r' : conecta("org.gjt.mm.mysql.Driver","jdbc:mysql://localhost/plixsite?user=plixsite_sii4bn&password=plixsite_sii4bn"); break;
		}
	}
	
	public void conecta(String driver, String url, String usuario, String senha){
		try {
			Class.forName(driver).newInstance();
			con = DriverManager.getConnection(url, usuario, senha);
		} catch(Exception e) {
			System.out.println(e);
		}
	}

	public void conecta(String driver, String url){
		try {
			Class.forName(driver).newInstance();
			con = DriverManager.getConnection(url);
		} catch(Exception e) {
			System.out.println(e);
		}
	}

	public ResultSet consulta(String sql) throws SQLException{
		Statement stmt = con.createStatement();
		stmt.executeQuery(sql);
		return stmt.getResultSet();
	}

	public void atualiza(String sql) throws SQLException{
		Statement stmt = con.createStatement();
		stmt.executeUpdate(sql);
	}

	public void visualiza(String tabela){
		try{
			ResultSet rs = consulta("SELECT * FROM "+tabela);
			ResultSetMetaData rsmd = rs.getMetaData();

			System.out.println(tabela);
			while( rs.next() ){
				for(int i=1; i<=rsmd.getColumnCount(); i++)
					System.out.print(rsmd.getColumnName(i)+":"+rs.getString(i)+" ");

				System.out.println("");
			}
		}catch(Exception e){
			System.out.println("ERRO:"+e.getMessage());
		}
	}

  	public void finalize () throws SQLException {
    	con.close();
  	}	
}
